﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;
using Media;
using System.Windows.Controls.Primitives;
using System.Xml.Serialization;
using System.Xml;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for LibraryView.xaml
    /// </summary>

    public partial class LibraryView : Page
    {
        #region "Properties"
        //private List<PlayList> list_playList = new List<PlayList>;
        public List<PlayList> list_playList { get; set; }
        public PlayList currentPlayList { get; set; }
        public PlayList defaultPlayList { get; set; }
        public PlayList playingPlayList { get; set; }
        int playingIndex = 0;
        bool isOnLibrary = false;
        bool isOnMusic = false;
        bool isOnPicture = false;
        bool isOnMovie = false;
       public Library library { get; set;}

        MainWindow mainWindow = null;
        #endregion

        #region "Library"
        public LibraryView(MainWindow window)
        {
            InitializeComponent();
            mainWindow = window;
            MediaGrid.CanUserAddRows = false;
            list_playList = new List<PlayList>();
            currentPlayList = new PlayList("");
            library = new Library();
            playingPlayList = null;

            defaultPlayList = currentPlayList;
            list_playList.Add(currentPlayList);
            loadLibrary();
            loadExistingPlayLists();

            
        }

        private void loadLibrary()
        {
            if (System.IO.File.Exists("./Library.xml") == true)
                library = Library.deSerialize("./Library.xml");                
            else
              library.importFilesFromLibraryFolders();
        }

        private void loadExistingPlayLists()
        {
            XmlSerializer xmls = new XmlSerializer(typeof(List<String>));
            List<String> tmp = new List<String>();
            XmlReader xmlx = XmlReader.Create("./PlayLists.xml");

            if (xmlx != null && xmls != null)
            {
                tmp = xmls.Deserialize(xmlx) as List<String>;

                foreach (String item in tmp)
                {
                    TreeViewItem newChild = new TreeViewItem();

                    newChild.Header = item;

                    playListsItem.Items.Add(newChild);
                    list_playList.Add(PlayList.deSerialize(item + ".xml"));                       
                }

                xmlx.Close();
            }
        }
        #endregion

        #region "Gestion TreeView"
        public void serialiseTreeViewItems()
        {
            XmlSerializer xmls = new XmlSerializer(typeof(List<String>));
            List<String> tmp = new List<String>();
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            settings.NewLineOnAttributes = true;

            XmlWriter xmlx = XmlWriter.Create("./PlayLists.xml", settings);


            foreach (TreeViewItem item in playListsItem.Items)
            {
                tmp.Add(item.Header.ToString());
            }

            if (xmlx != null && xmls != null)
            {
                xmls.Serialize(xmlx, tmp);
                xmlx.Close();
            }
        }

        private void leftTreeViewItemSelected(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)leftTreeView.SelectedItem;

            if (item != null)
            {
                if (rightTreeView.Items.Count >= 2)
                    rightTreeView.Items.RemoveAt(1);

                foreach (PlayList playListItem in list_playList)
                {
                    if (String.Compare(item.Header.ToString(), playListItem.getName()) == 0)
                    {
                        if (rightTreeView.Items.Count == 1)
                        {
                            putPlayListInCurrent(playListItem);
                            playCurrentPlayList();
                        }
                        break;
                    }
                }
            }            
        }

        private void leftTreeViewItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeViewItem item = (TreeViewItem)leftTreeView.SelectedItem;

            if (item != null)
            {
                foreach (PlayList playListItem in list_playList)
                {
                    isOnMusic = false;
                    isOnMovie = false;
                    isOnPicture = false;
                    isOnLibrary = false;

                    if (String.Compare(item.Header.ToString(), "Musics") == 0)
                        isOnMusic = true;
                    if (String.Compare(item.Header.ToString(), "Movies") == 0)
                        isOnMovie = true;
                    if (String.Compare(item.Header.ToString(), "Pictures") == 0)
                        isOnPicture = true;
                    if (String.Compare(item.Header.ToString(), "Library") == 0)
                        isOnLibrary = true;

                    if (isOnLibrary == true)
                    {
                        currentPlayList = library;
                        MediaGrid.ItemsSource = library.getList();
                        MediaGrid.Items.Refresh();
                    }
                    else if (isOnMovie == true)
                    {
                        MediaGrid.ItemsSource = library.getAllMovie();
                        MediaGrid.Items.Refresh();
                    }
                    else if (isOnMusic == true)
                    {
                        MediaGrid.ItemsSource = library.getAllMusic();
                        MediaGrid.Items.Refresh();
                    }
                    else if (isOnPicture == true)
                    {
                        MediaGrid.ItemsSource = library.getAllPicture();
                        MediaGrid.Items.Refresh();
                    }

                    if (String.Compare(item.Header.ToString(), "Playlists") == 0)
                    {
                        switchToPlayList(defaultPlayList);
                        break;
                    }
                    else if (String.Compare(item.Header.ToString(), playListItem.getName()) == 0)
                    {
                        switchToPlayList(playListItem);
                        break;
                    }
                }
            }
        }
        #endregion

        #region "Playlist"
        private bool isPlayListPlaying(PlayList playList)
        {
            if (rightTreeView.Items.Count > 1)
            {
                foreach (var item in rightTreeView.Items)
                {
                    TreeViewItem treeViewItem = item as TreeViewItem;

                    if (treeViewItem != null)
                    {
                        if (String.Compare(treeViewItem.Header.ToString(), playList.getName()) == 0)
                            return (true);
                    }
                }
            }
            return (false);
        }

        private void putPlayListInCurrent(PlayList playList)
        {
            if (playList != null)
            {

                TreeViewItem newPlayListItem = new TreeViewItem();

                newPlayListItem.Header = (String.IsNullOrEmpty(playList.getName()) == true) ? ("default playlist") : (playList.getName());

                foreach (AMediaInfo item in playList.getList())
                {
                    TreeViewItem newChild = new TreeViewItem();

                    newChild.Header = item.Title;
                    newPlayListItem.Items.Add(newChild);
                }

                rightTreeView.Items.Add(newPlayListItem);
                playingPlayList = playList;
            }
        }

        private void refreshPlayListPlaying()
        {
            rightTreeView.Items.RemoveAt(1);
            putPlayListInCurrent(currentPlayList);
        }

        private void refreshMediaView()
        {
            if (isPlayListPlaying(currentPlayList) == true)
            {
                refreshPlayListPlaying();
            }

            if (isOnMovie == true)
            {
                MediaGrid.ItemsSource = library.getAllMovie();
                MediaGrid.Items.Refresh();
            }
            else if (isOnMusic == true)
            {
                MediaGrid.ItemsSource = library.getAllMusic();
                MediaGrid.Items.Refresh();
            }
            else if (isOnPicture == true)
            {
                MediaGrid.ItemsSource = library.getAllPicture();
                MediaGrid.Items.Refresh();
            }
            else
                switchToPlayList(currentPlayList);
        }

        public void switchToPlayList(PlayList playList)
        {
            currentPlayList = playList;

            MediaGrid.ItemsSource = currentPlayList.getList();
            MediaGrid.Items.Refresh();
        }

        private void createNewPlayList(object sender, RoutedEventArgs e)
        {
            playListForm window = new playListForm(this, list_playList);

            System.Diagnostics.Debug.WriteLine("ActualWidth : " + window.MinWidth);

            double left = mainWindow.Left + ((mainWindow.ActualWidth / 2) - (window.Width / 2));
            double top = mainWindow.Top + ((mainWindow.ActualHeight / 2) - (window.Height / 2));

            window.Left = left;
            window.Top = top;

            window.Show();
        }

        private void checkAndSetInfo(AMediaInfo MediaDrop)
        {
            if (MediaDrop.getTitle() == null)
                MediaDrop.setTitle("Aucune référence");
            if (MediaDrop.getAuthor() == null)
                MediaDrop.setAuthor("Aucune référence");
        }

        private void playCurrentPlayList()
        {
            if (rightTreeView.Items.Count >= 2)
            {
                TreeViewItem playListItem = (TreeViewItem)rightTreeView.Items.GetItemAt(1);

                if (playListItem != null)
                {
                    if (playListItem.Items.Count > 0)
                    {
                        TreeViewItem firstChildItem = (TreeViewItem)playListItem.Items.GetItemAt(0);

                        if (firstChildItem != null)
                        {
                            firstChildItem.IsSelected = true;
                            AMediaInfo mediaInfo = playingPlayList.getMediaById(0);

                            if (mediaInfo != null)
                            {
                                playingIndex = 0;
                                mainWindow.playMediaWithPath(mediaInfo.FilePath);
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region Creation de la List de Musique Info
        private void LoadCollectionMedia(DragEventArgs e, string[] droppedFilePaths)
        {
            foreach (string droppedFilePath in droppedFilePaths)
            {
                if (Directory.Exists(droppedFilePath) == true)
                {
                    currentPlayList.getMediaInfoFromFolder(droppedFilePath);
                }
                else
                {
                    AMediaInfo MediaDrop = Media.MediaInfoFactory.getInfoOfMedia(droppedFilePath);
                    checkAndSetInfo(MediaDrop);
                    currentPlayList.addElem(MediaDrop);
                }
            }

            if (currentPlayList != defaultPlayList)
                currentPlayList.serialize("./" + currentPlayList.getName() + ".xml");
            
            if (isPlayListPlaying(currentPlayList) == true)
                refreshPlayListPlaying();
        }
        #endregion

        #region Gestion du drag and drop
        private void FilesDropped(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
                LoadCollectionMedia(e, droppedFilePaths);
                MediaGrid.ItemsSource = currentPlayList.getList();
                MediaGrid.Items.Refresh();
            }
        }
        #endregion

        #region "Event"
        private void rightTreeViewKeyUp(object sender, KeyEventArgs args)
        {
            if (args.Key == Key.Delete)
            {

                TreeViewItem currentItem = rightTreeView.SelectedItem as TreeViewItem;

                if (currentItem != null)
                {
                    if (String.Compare(currentItem.Header.ToString(), "Current Playlist") != 0)
                    {
                        AMediaInfo ret = (AMediaInfo)currentPlayList.getList().Find(v => v.getTitle().CompareTo(currentItem.Header.ToString()) == 0);

                        if (ret != null)
                        {
                            currentPlayList.removeElem(ret);
                            refreshMediaView();
                        }
                        else
                        {
                            rightTreeView.Items.Remove(currentItem);
                            playingPlayList = null;
                        }
                    }
                }
            }
        }

        private void leftTreeViewKeyUp(object sender, KeyEventArgs args)
        {
            if (args.Key == Key.Delete)
            {
                TreeViewItem currentItem = leftTreeView.SelectedItem as TreeViewItem;

                if (currentItem != null)
                {
                    if (isOnLibrary == false && isOnMovie == false && isOnMusic == false && isOnPicture == false &&
                        String.Compare(currentItem.Header.ToString(), "Playlists") != 0)
                    {
                        PlayList ret = (PlayList)list_playList.Find(v => v.getName().CompareTo(currentItem.Header.ToString()) == 0);

                        if (ret != null)
                            playListsItem.Items.Remove(currentItem);

                        defaultPlayList.getList().Clear();
                        switchToPlayList(defaultPlayList);
                    }
                }
            }            
        }

        private void rightTreeViewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem treeViewItem = (TreeViewItem)rightTreeView.SelectedItem;

            if (treeViewItem != null)
            {
                if (treeViewItem.Items.Count == 0 && String.Compare(treeViewItem.Header.ToString(), "Current Playlist") != 0)
                {
                    TreeViewItem playlistItem = (TreeViewItem)treeViewItem.Parent;

                    if (playlistItem != null)
                    {
                       int index = playlistItem.Items.IndexOf(treeViewItem);

                       if (playingPlayList != null)
                       {
                           AMediaInfo mediaInfo = playingPlayList.getMediaById(index);

                           if (mediaInfo != null)
                           {
                               playingIndex = index;
                               mainWindow.playMediaWithPath(mediaInfo.FilePath);
                           }
                       }
                    }
                }
                else if (String.Compare(treeViewItem.Header.ToString(), currentPlayList.getName()) == 0)
                {
                    if (treeViewItem.Items.Count > 0)
                    {
                        AMediaInfo mediaInfo = playingPlayList.getMediaById(0);

                        if (mediaInfo != null)
                        {
                            playingIndex = 0;
                            mainWindow.playMediaWithPath(mediaInfo.FilePath);
                        }
                    }
                }
            }
        }

        private void onKeyUp(object sender, System.Windows.Input.KeyEventArgs args)
        {
            if (args.Key == Key.Delete)
            {
                foreach (var item in MediaGrid.SelectedItems)
                {
                    AMediaInfo media = item as AMediaInfo;
                    currentPlayList.removeElem(media);

                    if (currentPlayList != defaultPlayList)
                        currentPlayList.serialize("./" + currentPlayList.getName() + ".xml");
                }

                refreshMediaView();
            }
        }

        private void MediaGridMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            System.Collections.IList selector = MediaGrid.SelectedItems;

            defaultPlayList.getList().Clear();

            if (rightTreeView.Items.Count >= 2)
            {
                rightTreeView.Items.RemoveAt(1);
            }

            foreach (var item in selector)
            {
                AMediaInfo mediaInfo = item as AMediaInfo;

                if (mediaInfo != null)
                    defaultPlayList.addElem(mediaInfo);
            }

            putPlayListInCurrent(defaultPlayList);
            playCurrentPlayList();
        }
        #endregion

        #region "Media"
        public void playNextMedia()
        {
            if (playingPlayList != null && rightTreeView.Items.Count >= 2)
                {
                    AMediaInfo mediaInfo = playingPlayList.getMediaById(playingIndex + 1);
                    TreeViewItem playlistItem = (TreeViewItem)rightTreeView.Items.GetItemAt(1);
                    TreeViewItem currentMediaItem = null;

                    if (mediaInfo != null)
                    {
                        playingIndex++;

                        if (playlistItem != null)
                        {
                            currentMediaItem = (TreeViewItem)playlistItem.Items.GetItemAt(playingIndex);

                            if (currentMediaItem != null)
                                currentMediaItem.IsSelected = true;
                        }

                        mainWindow.playMediaWithPath(mediaInfo.FilePath);
                    }
                    else
                    {
                        mediaInfo = playingPlayList.getMediaById(0);

                        if (mediaInfo != null)
                        {
                            playingIndex = 0;


                            if (playlistItem != null)
                            {
                                currentMediaItem = (TreeViewItem)playlistItem.Items.GetItemAt(playingIndex);

                                if (currentMediaItem != null)
                                    currentMediaItem.IsSelected = true;
                            }

                            mainWindow.playMediaWithPath(mediaInfo.FilePath);
                        }
                    }
                }
        }

        public void playPreviousMedia()
        {
            if (playingPlayList != null && rightTreeView.Items.Count >= 2)
            {
                AMediaInfo mediaInfo = playingPlayList.getMediaById(playingIndex - 1);
                TreeViewItem playlistItem = (TreeViewItem)rightTreeView.Items.GetItemAt(1);
                TreeViewItem currentMediaItem = null;

                if (mediaInfo != null)
                {
                    playingIndex--;

                    if (playlistItem != null)
                    {
                        currentMediaItem = (TreeViewItem)playlistItem.Items.GetItemAt(playingIndex);

                        if (currentMediaItem != null)
                            currentMediaItem.IsSelected = true;
                    }

                    mainWindow.playMediaWithPath(mediaInfo.FilePath);
                }
                else
                {
                    int count = playingPlayList.getList().Count;
                    mediaInfo = playingPlayList.getMediaById(count - 1);

                    if (mediaInfo != null)
                    {
                        playingIndex = (count - 1);

                        if (playlistItem != null)
                        {
                            currentMediaItem = (TreeViewItem)playlistItem.Items.GetItemAt(playingIndex);

                            if (currentMediaItem != null)
                                currentMediaItem.IsSelected = true;
                        }

                        mainWindow.playMediaWithPath(mediaInfo.FilePath);
                    }
                }
            }
        }
        #endregion

        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void MediaGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}